import { customerDownloadInvoiceTemplateApi } from "@/api/client/documentManagement/waybillManagement";
import { importDepositApi, downWaterExcelApi, verifyExcelApi } from "@/api/financialManagement/receivable/waterVerification";
import CommonHook from "@/hook/commonHook";
import { message } from "ant-design-vue";
import { Ref } from "vue";

export default function OperationHook(state: {
  formState: { fileList: Array<File> };
  step: Ref<number>;
  loading: Ref<boolean>;
  emit: any;
  validateData: {
    passDepositList: Array<Base.GeneraDataType>;
    failDepositList: Array<Base.GeneraDataType>;
    passDepositSummaryList: Array<Base.GeneraDataType>;
  };
}) {
  const { formState, step, validateData, loading, emit } = state;
  const { downloadFileByBlob } = CommonHook();
  const uploadRequest = (e: any) => {
    formState.fileList = [e.file];
    e.onProgress({ percent: 100 });
  };
  // 数据校验
  const dataValidateHandle = () => {
    if (!formState.fileList.length) return message.error("请先上传文件!");
    const formData = new FormData();
    formData.append("file", formState.fileList[0]);
    loading.value = true;
    return verifyExcelApi(formData)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          message.success("数据校验完成!");
          step.value = 2;
          validateData.failDepositList = data.failDepositList || [];
          validateData.passDepositList = data.passDepositList || [];
          validateData.passDepositSummaryList = data.passDepositSummaryList || [];
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  // 下载模板
  const downloadTemplateHandle = () => {
    return customerDownloadInvoiceTemplateApi("import_deposit.xlsx").then((res: any) => {
      downloadFileByBlob(res, "批量导入来款.xlsx");
    });
  };
  // 导出失败数据
  const exportFailDepositHandle = () => {
    return downWaterExcelApi(validateData).then((res: any) => {
      downloadFileByBlob(res, "不可导入数据.xlsx");
      message.success("操作成功!");
    });
  };
  // 导入来款流水
  const importDepositHandle = () => {
    if (!validateData.passDepositList.length) return message.info("没有可导入的数据!");
    return importDepositApi(validateData).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("操作成功!");
        emit("submit");
      }
    });
  };
  return {
    uploadRequest,
    dataValidateHandle,
    downloadTemplateHandle,
    exportFailDepositHandle,
    importDepositHandle
  };
}
